package com.flowplan.project.service;

import com.flowplan.entity.Project;
import com.flowplan.entity.SysUser;
import com.flowplan.entity.enums.ProjectStatus;
import com.flowplan.project.dto.ProjectCreateRequest;
import com.flowplan.project.dto.ProjectResponse;
import com.flowplan.project.dto.ProjectUpdateRequest;
import com.flowplan.project.repository.ProjectRepository;
import com.flowplan.auth.repository.SysUserRepository;
import com.flowplan.todo.repository.TodoRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目服务实现类
 * 
 * @author FlowPlan Team
 */
@Slf4j
@Service
public class ProjectService {
    
    @Autowired
    private ProjectRepository projectRepository;
    
    @Autowired
    private SysUserRepository userRepository;
    
    @Autowired
    private TodoRepository todoRepository;
    
    /**
     * 创建项目
     */
    @Transactional
    public ProjectResponse createProject(ProjectCreateRequest request, Long creatorId) {
        log.info("用户 {} 创建项目: {}", creatorId, request.getProjectName());
        
        // 验证创建人是否存在
        SysUser creator = userRepository.findById(creatorId)
                .orElseThrow(() -> new RuntimeException("创建人不存在"));
        
        // 检查项目名称是否重复
        if (projectRepository.findByProjectName(request.getProjectName()).isPresent()) {
            throw new RuntimeException("项目名称已存在");
        }
        
        // 创建项目实体
        Project project = Project.builder()
                .projectName(request.getProjectName())
                .description(request.getDescription())
                .status(ProjectStatus.PLANNING)
                .priority(request.getPriority())
                .creatorId(creatorId)
                .creator(creator)  // 设置creator对象
                .deadline(request.getDeadline())
                .build();
        
        Project savedProject = projectRepository.save(project);
        
        log.info("项目创建成功，ID: {}", savedProject.getId());
        return convertToResponse(savedProject);
    }
    
    /**
     * 更新项目
     */
    @Transactional
    public ProjectResponse updateProject(Long projectId, ProjectUpdateRequest request, Long userId) {
        log.info("用户 {} 更新项目 {}", userId, projectId);
        
        Project project = projectRepository.findById(projectId)
                .orElseThrow(() -> new RuntimeException("项目不存在"));
        
        // 只有项目创建者才能更新项目
        if (!project.getCreatorId().equals(userId)) {
            throw new RuntimeException("无权限更新此项目");
        }
        
        // 更新项目信息
        if (request.getProjectName() != null) {
            // 检查新名称是否与其他项目重复
            projectRepository.findByProjectName(request.getProjectName())
                    .ifPresent(existingProject -> {
                        if (!existingProject.getId().equals(projectId)) {
                            throw new RuntimeException("项目名称已存在");
                        }
                    });
            project.setProjectName(request.getProjectName());
        }
        
        if (request.getDescription() != null) {
            project.setDescription(request.getDescription());
        }
        
        if (request.getStatus() != null) {
            project.setStatus(request.getStatus());
        }
        
        if (request.getPriority() != null) {
            project.setPriority(request.getPriority());
        }
        
        if (request.getDeadline() != null) {
            project.setDeadline(request.getDeadline());
        }
        
        Project updatedProject = projectRepository.save(project);
        
        log.info("项目更新成功，ID: {}", projectId);
        return convertToResponse(updatedProject);
    }
    
    /**
     * 删除项目
     */
    @Transactional
    public void deleteProject(Long projectId, Long userId) {
        log.info("用户 {} 删除项目 {}", userId, projectId);
        
        Project project = projectRepository.findById(projectId)
                .orElseThrow(() -> new RuntimeException("项目不存在"));
        
        // 只有项目创建者才能删除项目
        if (!project.getCreatorId().equals(userId)) {
            throw new RuntimeException("无权限删除此项目");
        }
        
        // 删除项目相关的所有数据（待办任务、Excel计划等）
        
        projectRepository.delete(project);
        log.info("项目删除成功，ID: {}", projectId);
    }
    
    /**
     * 获取项目详情
     */
    @Transactional(readOnly = true)
    public ProjectResponse getProject(Long projectId) {
        Project project = projectRepository.findById(projectId)
                .orElseThrow(() -> new RuntimeException("项目不存在"));
        
        return convertToResponse(project);
    }
    
    /**
     * 分页查询项目列表
     */
    @Transactional(readOnly = true)
    public Page<ProjectResponse> getProjects(ProjectStatus status, Long creatorId, String keyword, 
                                           int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        
        Page<Project> projectPage = projectRepository.findProjectsWithConditions(
                status, creatorId, keyword, pageable);
        
        return projectPage.map(this::convertToResponse);
    }
    
    /**
     * 获取用户创建的项目列表
     */
    @Transactional(readOnly = true)
    public List<ProjectResponse> getUserProjects(Long userId) {
        List<Project> projects = projectRepository.findByCreatorIdOrderByCreateTimeDesc(userId);
        return projects.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 获取即将到期的项目
     */
    @Transactional(readOnly = true)
    public List<ProjectResponse> getProjectsNearDeadline() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime deadlineLimit = now.plusDays(7);
        
        List<Project> projects = projectRepository.findProjectsNearDeadline(now, deadlineLimit);
        return projects.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 获取已过期的项目
     */
    @Transactional(readOnly = true)
    public List<ProjectResponse> getOverdueProjects() {
        LocalDateTime now = LocalDateTime.now();
        
        List<Project> projects = projectRepository.findOverdueProjects(now);
        return projects.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 转换为响应DTO
     */
    private ProjectResponse convertToResponse(Project project) {
        // 统计待办任务
        ProjectResponse.TodoStats todoStats = buildTodoStats(project.getId());
        
        return ProjectResponse.builder()
                .id(project.getId())
                .projectName(project.getProjectName())
                .description(project.getDescription())
                .status(project.getStatus())
                .priority(project.getPriority())
                .creatorId(project.getCreatorId())
                .creatorName(project.getCreator() != null ? project.getCreator().getUsername() : null)
                .deadline(project.getDeadline())
                .createTime(project.getCreateTime())
                .updateTime(project.getUpdateTime())
                .todoStats(todoStats)
                .excelPlanCount(project.getExcelPlans() != null ? project.getExcelPlans().size() : 0)
                .build();
    }
    
    /**
     * 构建待办任务统计
     */
    private ProjectResponse.TodoStats buildTodoStats(Long projectId) {
        // 实现待办任务统计逻辑
        return ProjectResponse.TodoStats.builder()
                .total(0)
                .completed(0)
                .inProgress(0)
                .todo(0)
                .blocked(0)
                .build();
    }
}